package com.cheung.leetcode.backtrack;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.backtrack
 * @Author :  cheungming
 * @CreateTime : 2024-05-28 16:46:17
 * @Description : N-Queens
 * @Version : 1.0
 */
public class Code51Test {

    public List<List<String>> solveNQueens(int n) {
        char[][] board = new char[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                board[i][j] = '.';
            }
        }
        List<List<String>> res = new ArrayList<>();
        backtrack(res, board, 0, n);
        return res;
    }

    public void backtrack(List<List<String>> res, char[][] board, int row, int n) {
        if (row == n) {
            res.add(convert(board));
            return;
        }

        for (int i = 0; i < n; i++) {
            if (!isValid(board, n, row, i)) {
                continue;
            }
            board[row][i] = 'Q';
            backtrack(res, board, row + 1, n);
            board[row][i] = '.';
        }
    }

    public List<String> convert(char[][] chessboard) {
        List<String> list = new ArrayList<>();

        for (char[] c : chessboard) {
            list.add(String.copyValueOf(c));
        }
        return list;
    }


    public boolean isValid(char[][] board, int n, int row, int col) {
        // 判断皇后是否合法
        // 判断当前一列是否有皇后
        for (int i = 0; i < n; i++) {
            if (board[i][col] == 'Q') {
                return false;
            }
        }

        // 判断当前一行是否有皇后
        for (int i = 0; i < n; i++) {
            if (board[row][i] == 'Q') {
                return false;
            }
        }

        // 检查45度对角线
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
            if (board[i][j] == 'Q') {
                return false;
            }
        }

        // 检查135度对角线
        for (int i = row - 1, j = col + 1; i >= 0 && j <= n - 1; i--, j++) {
            if (board[i][j] == 'Q') {
                return false;
            }
        }


        return true;
    }

    @Test
    public void test1() {
        int n = 4;
        assert solveNQueens(n).size() == 2;
    }

    @Test
    public void test2() {
        int n = 1;
        assert solveNQueens(n).size() == 1;
    }
}
